<template>
  <el-container class="app-container">
    <el-form ref="form" :model="form" :rules="rules" label-width="140px">
      <!--  <el-header></el-header>-->
      <el-card class="box-card">
        <div slot="header" class="clearfix  box-card-h">
          <span>合同信息</span>
        </div>
        <div>
          <el-row class="p-style">
            <el-col :span="12">
              <el-form-item prop="areaName" label="所属办公空间:">
               {{roomDetail.areaName}}
                <span class="p-r-15">{{roomDetail.buildingNo}}幢{{roomDetail.buildingFloor}}楼{{roomDetail.roomNo}}室</span>
              </el-form-item>

              <el-form-item prop="area" label="面积（m²）:" placeholder="租赁面积">
                {{roomDetail.measureArea}}
              </el-form-item>

              <el-form-item prop="followerId" label="跟进人：">
                <el-select v-model="form.followerId" placeholder="请选择">
                  <el-option
                    v-for="item in userOptions"
                    :key="item.userId"
                    :label="item.userName"
                    :value="item.userId">
                  </el-option>
                </el-select>
              </el-form-item>
              <el-form-item prop="lesseeId" label="租户主体：">
                <el-select v-model="form.lesseeId" placeholder="请选择">
                  <el-option
                    v-for="(item,i) in tenantOptions"
                    :key="i"
                    :label="item.name"
                    :value="item.id">
                  </el-option>
                </el-select>
              </el-form-item>
              <el-form-item prop="labelIds" label="合同标签：">
                <el-select
                  v-model="form.labelIds"
                  multiple
                  placeholder="请选择">
                  <el-option
                    v-for="(item,i) in contractLabels"
                    :key="i"
                    :label="item.labelName"
                    :value="item.id">
                  </el-option>
                </el-select>
                <el-button type="" size="mini" icon="el-icon-plus" @click="addLabel">新增标签</el-button>
              </el-form-item>
              <el-form-item prop="remark" label="备注：">
                <el-input v-model.trim='form.contractFeeRule.remark' type="textarea" placeholder="请输入"></el-input>
              </el-form-item>
            </el-col>


            <el-col :span="12">
              <el-form-item prop="contractNo" label="合同编号：">
                <el-input v-model.trim='form.contractFeeRule.contractNo' placeholder="如不填写系统将自动生成"></el-input>
              </el-form-item>
              <el-form-item prop="signedDate" label="合同签订日：">
                <el-date-picker
                  v-model="form.signedDate"
                  type="date"
                  value-format="yyyy-MM-dd"
                  placeholder="选择日期">
                </el-date-picker>
            </el-form-item>
              <el-form-item prop="rentalDate" label="合同计租日：">
                <el-date-picker
                  v-model="form.rentalDate"
                  type="date"
                  value-format="yyyy-MM-dd"
                  placeholder="选择日期">
                </el-date-picker>
              </el-form-item>
              <el-form-item prop="rentalDueDate" label="合同结束日：">
                <el-date-picker
                  v-model="form.rentalDueDate"
                  type="date"
                  value-format="yyyy-MM-dd"
                  placeholder="选择日期">
                </el-date-picker>
              </el-form-item>
              <el-form-item prop="price" label="合同单价：">
                <el-input v-model.trim="form.contractFeeRule.price" style="width: 200px"></el-input>
                <el-radio-group v-model="form.contractFeeRule.priceUnit">
                  <el-radio :label="1">元/㎡/天</el-radio>
                  <el-radio :label="2">元/月</el-radio>
                </el-radio-group>
              </el-form-item>
              <el-form-item prop="paymentSecurityMonthes" label="付款方式：">
                押
                <el-input v-model.trim='form.contractFeeRule.paymentSecurityMonthes' placeholder="请输入" style="width: 100px"></el-input>
                付
                <el-input v-model.trim='form.contractFeeRule.paymentMonthes' placeholder="请输入" style="width: 100px"></el-input>
              </el-form-item>
              <el-form-item prop="paymentDeadline" label="付款要求：">
                前
                <el-input v-model.trim='form.contractFeeRule.paymentDeadline' placeholder="请输入" style="width: 100px"></el-input>
                天，支付下一期租金
              </el-form-item>
              <el-form-item prop="incrementalRuleYear" label="租金递增：">
                每
                <el-input v-model.trim='form.contractFeeRule.incrementalRuleYear' placeholder="请输入" style="width: 100px"></el-input>
                年，递增
                <el-input v-model.trim="form.contractFeeRule.incrementalRuleValue" style="width: 100px"></el-input>
                <el-radio-group v-model="form.contractFeeRule.incrementalRuleUnit">
                  <el-radio :label="1">%</el-radio>
                  <el-radio :label="2">元</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
          </el-row>

          <el-collapse v-model="activeNameszj" @change="contractFee" class="collapse">
            <el-collapse-item title="点击生成租金明细" name="1">
              <h5>保证金</h5>
              <table-view
                :columns="tableContentbzj"
                :pageList="columnDatabzj"
                :templateDiv="{paymentStatus:true}"
              >
                <template slot="paymentStatus" slot-scope="scope">
                  {{{0:'未付款',1:'已付款'}[scope.row.paymentStatus]}}
                 </template>
              </table-view>
              <h5>租金</h5>
              <table-view
                :columns="tableContentzj"
                :pageList="columnDatazj"
                :templateDiv="{paymentStatus:true,payDeadline:true}"
              >
                <template slot="paymentStatus" slot-scope="scope">
                  {{{0:'未付款',1:'已付款'}[scope.row.paymentStatus]}}
                </template>
                <template slot="payDeadline" slot-scope="scope">
                  提前{{scope.row.paymentStatus}}天
                </template>
              </table-view>
            </el-collapse-item>
          </el-collapse>

        </div>
      </el-card>


      <el-card class="box-card">
        <div slot="header" class="clearfix  box-card-h">
          <span>物业费</span>
        </div>
        <div>
          <el-row class="p-style">
            <el-col :span="8">
              <!--<el-form-item prop="rentalDate" label="开始时间：">
                <el-date-picker
                  v-model="form.propertyCostsFeeRule.rentalDate"
                  type="date"
                  value-format="yyyy-MM-dd"
                  placeholder="选择日期">
                </el-date-picker>
              </el-form-item>-->

              <el-form-item prop="paymentMonthes" label="付款方式：">
                每
                <el-input v-model.trim='form.propertyCostsFeeRule.paymentMonthes' placeholder="请输入" style="width: 100px"></el-input>
                个月一付
              </el-form-item>

            </el-col>
            <el-col :span="8">
              <!--<el-form-item prop="title" label="结束时间：">
                <el-date-picker
                  v-model="form.propertyCostsFeeRule.rentalDueDate"
                  type="date"
                  value-format="yyyy-MM-dd"
                  placeholder="选择日期">
                </el-date-picker>
              </el-form-item>-->
              <el-form-item prop="title" label="付款要求：">
                前
                <el-input v-model.trim='form.propertyCostsFeeRule.paymentDeadline' placeholder="请输入" style="width: 100px"></el-input>
                天，支付下一期物业费
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item prop="title" label="计费单价：">
                <el-input v-model.trim="form.propertyCostsFeeRule.price" style="width: 200px"></el-input>
                <el-radio-group v-model="form.propertyCostsFeeRule.priceUnit">
                  <el-radio :label="1">元/㎡/天</el-radio>
                  <el-radio :label="2">元/月</el-radio>
                </el-radio-group>
              </el-form-item>
              <el-form-item prop="title" label="物业费备注：">
                <el-input v-model.trim='form.propertyCostsFeeRule.remark' type="textarea" placeholder="请输入"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
        </div>

        <el-collapse v-model="activeNameswyf" @change="contractFee" class="collapse">
          <el-collapse-item title="点击生成物业费明细" name="2">
            <h5>物业费</h5>
            <table-view
              :columns="tableContentwyf"
              :pageList="columnDatawyf"
              :templateDiv="{paymentStatus:true,payDeadline:true}"
            >
              <template slot="paymentStatus" slot-scope="scope">
                {{{0:'未付款',1:'已付款'}[scope.row.paymentStatus]}}
              </template>
              <template slot="payDeadline" slot-scope="scope">
                提前{{scope.row.paymentStatus}}天
              </template>
            </table-view>
          </el-collapse-item>
        </el-collapse>
      </el-card>

      <el-card class="box-card">

        <el-button type="primary" @click="onSubmit">保存</el-button>
        <el-button @click="()=>{this.$router.go(-1)}">取消</el-button>

      </el-card>

    </el-form>


    <el-dialog title="新增标签" :visible.sync="dialogAddLabel" width="60%"
               :destroy-on-close="true">
      <el-form ref="form" :model="formLabel" :rules="rulesLabel" label-width="120px" style="width: 90%">
        <el-form-item prop="labelName" label="标签名称:">
          <el-input v-model.trim="formLabel.labelName"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="onSubmitLabel">保存</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
    <el-footer></el-footer>
  </el-container>
</template>

<script>
  import TableView from '@/components/TableView'

  import * as pageApi from '@/api/spaceBusiness/houseManage/contract'
  import * as spaceApi from '@/api/spaceBusiness/spaceManage'
  import * as commonApi from '@/api/common'
  import * as tenantApi from '@/api/spaceBusiness/tenantManageList'


  export default {
    name: 'add',
    components: {
      TableView
    },
    data() {
      return {
        tenantOptions:[],
        roomDetail:{},
        activeNameswyf:[],
        activeNameszj:[],
        userOptions:[],
        spaceOptions: [],
        contractLabels:[],
        dialogAddLabel:false,
        tableContentbzj:[{
          field: 'fee',
          label: '保证金'
        }, {
          field: 'paymentStatus',
          label: '付款状态'
        }, {
          field: 'paymentDate',
          label: ' 付款日期'
        }, {
          field: 'remark',
          label: ' 保证金备注'
        }, ],
        columnDatabzj:[],
        tableContentzj:[{
          field: 'periods',
          label: '期数'
        }, {
          field: 'startDate',
          label: '开始日期'
        }, {
          field: 'fee',
          label: '租金'
        }, {
          field: 'payDeadline',
          label: ' 付款要求'
        },{
          field: 'paymentCycle',
          label: '付款周期'
        }, {
          field: 'paymentStatus',
          label: '付款状态'
        }, {
          field: 'paymentDate',
          label: ' 付款日期'
        },{
          field: 'delayDays',
          label: '滞纳天数'
        }, {
          field: 'remark',
          label: '合同备注'
        }],
        columnDatazj:[],
        tableContentwyf:[{
          field: 'periods',
          label: '期数'
        }, {
          field: 'startDate',
          label: '开始日期'
        }, {
          field: 'fee',
          label: '租金'
        }, {
          field: 'payDeadline',
          label: ' 付款要求'
        },{
          field: 'paymentCycle',
          label: '付款周期'
        }, {
          field: 'paymentStatus',
          label: '付款状态'
        }, {
          field: 'paymentDate',
          label: ' 付款日期'
        },{
          field: 'delayDays',
          label: '滞纳天数'
        }, {
          field: 'remark',
          label: '合同备注'
        }],
        columnDatawyf:[],
        formLabel:{
          labelName:'',
          labelType:''
        },
        rulesLabel:[{
          labelName: { required: true, trigger: 'blur', message: '名称不能为空' },
        }],

        form: {
          measureArea:'',
          "contractFeeRule": {
            "incrementalRuleUnit": '',
            "incrementalRuleValue": '',
            "incrementalRuleYear": '',
            "paymentDeadline": '',
            "paymentMonthes": '',
            "paymentSecurityMonthes": '',
            "price": '',
            "priceUnit": '',
            "remark": ""
          },
          "contractNo": "",
          "followerId": '',
          "labelIds": "",
          "lesseeId": '',
          "propertyCostsFeeRule": {
            "paymentDeadline": '',
            "paymentMonthes": '',
            "price": '',
            "priceUnit": '',
            "remark": ""
          },
          "rentalDate": "",
          "rentalDueDate": "",
          "roomId": '',
          "signedDate": ""

        },
        rules: {
          followerId:[{required: true, trigger: 'blur', message: '跟进人不能为空'}],
          lesseeId:[{required: true, trigger: 'blur', message: '租户主体不能为空'}],
          signedDate:[{required: true, trigger: 'blur', message: '签订日不能为空'}],
          rentalDate:[{required: true, trigger: 'blur', message: '计租日不能为空'}],
          rentalDueDate:[{required: true, trigger: 'blur', message: '结束日不能为空'}],
          name: [
            {required: true, trigger: 'blur', message: '名称不能为空'},
            {min: 1, max: 20, message: '长度不能超过20个汉字'}
          ],
          content: [{required: true, trigger: 'blur', message: '请填写内容'}]
        }

      }
    },
    methods: {
      addLabel(){
        this.formLabel = {
          labelName:'',
          labelType:0
        }
        this.dialogAddLabel = true
      },
      onSubmitLabel(){
        commonApi.addLabel(this.formLabel).then(res=>{
          this.handleMessage(res)
          if(res.code === '200'){
            this.dialogAddLabel = false
            this.getAllLabel()
          }
        })
      },
      handleRes(res) {
        let _this = this
        if (res.code === '200') {
          _this.$message.success(res.message)
          _this.$router.go(-1)
        } else {
          _this.$message.error(res.message)
        }
      },
      onSubmit() {
        let _this = this
        let postData = Object.assign({},_this.form)
        postData.labelIds = postData.labelIds.join(',')
        if(Object.values(postData.propertyCostsFeeRule).some(item=>item)){
            let {paymentDeadline,paymentMonthes,price,priceUnit}= postData.propertyCostsFeeRule
          if(!paymentDeadline||!paymentMonthes ||!price || !priceUnit){
            return _this.$message.error('物业费规则请填写完整')
          }
        }else{
          postData.propertyCostsFeeRule = null
        }
        _this.$refs['form'].validate((valid) => {
          if (valid) {
              pageApi.create(postData).then((res) => {
                _this.handleRes(res)
              })
            }
        })
      },
      backClick() {
        this.$router.go(-1)
      },
      getById(id) {
        pageApi.getById(id).then(res => {
          setTimeout(() => {
            this.form = Object.assign({}, this.form, res.body)
          }, 0)
        })
      },
      //拉取空间list
      getSpaceList() {
        spaceApi.getAreaAll().then(res => {
          this.spaceOptions = res.body
        })
      },
      getAllLabel(){
        //服务标签
        commonApi.getAllLabel(0).then(res=>{
          this.contractLabels = res.body
        })
      },
      getUserList(){
        pageApi.getUserList().then(res=>{
          this.userOptions = res.body
        })
      },
      contractFee(val){
        let formCopy = JSON.parse(JSON.stringify(this.form))
        let postData = {}
        if(val[0]==='1'){
           postData = Object.assign({},this.form.contractFeeRule)
        }else{
          postData = Object.assign({},this.form.propertyCostsFeeRule)
        }

        postData.measureArea = formCopy.measureArea
        postData.rentalDate = formCopy.rentalDate
        postData.rentalDueDate = formCopy.rentalDueDate

        pageApi.contractFee(postData).then(res=>{
          if(val[0]==='1'){
            this.columnDatabzj = [res.body.securityFee]
            this.columnDatazj = res.body.rent
          }else{
            this.columnDatawyf = res.body.rent
          }
        })
      },
      getTenantList(){
        tenantApi.getList({pageSize: 100}).then(res => {
            this.tenantOptions = res.body.records
        })
      }
    },
    created: function () {
      let {id,roomDetail} = this.$route.query
      roomDetail = JSON.parse(roomDetail)
      this.form.measureArea = roomDetail.measureArea
      this.roomDetail = roomDetail
      this.form.roomId  = id
      // this.getSpaceList()
      this.getAllLabel()
      this.getUserList()
      this.getTenantList()
    }
  }
</script>

<style lang="scss" scoped>
  .tags {
    margin-right: 10px;
  }

  .p-style {
    font-pageSize: 14px;
  }

  .box-card {
    .box-card-h {
      font-pageSize: 16px;
      font-weight: 500;
    }
  }
  .collapse{
    .el-collapse-item{
      .el-collapse-item__header{
        color: #1e6abc;
      }
    }
  }
</style>
